package mp

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/common/constants"
	pb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/base/user/mp"
)

type mpRepository struct{}

// NewMpRepository
// 构造函数
func NewMpRepository() mp.MpRepositoryIface {
	return &mpRepository{}
}

// GetMiniProgramOpenId
// 获取小程序openid
func (r *mpRepository) GetMiniProgramOpenId(ctx context.Context, code string) (*mp.MPLoginInfo, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_USER_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewMiniProgramServiceClient(conn)
	data, err := client.GetMiniProgramOpenId(ctx, &pb.GetMiniProgramOpenIdRequest{Code: code})
	if err != nil {
		return nil, err
	}
	loginInfo := &mp.MPLoginInfo{}
	if data != nil {
		loginInfo.OpenId = data.Openid
		loginInfo.UnionId = data.Unionid
		loginInfo.SessionKey = data.SessionKey
	}
	return loginInfo, nil
}

// GetMpAccessToken
// 获取accesstoken
func (r *mpRepository) GetMpAccessToken(ctx context.Context) (resp *pb.GetAccessTokenResponse, err error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_USER_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewMiniProgramServiceClient(conn)
	return client.GetAccessToken(ctx, &pb.GetAccessTokenRequest{})
}

// CleanMpAccessToken 清理缓存
func (r *mpRepository) CleanMpAccessToken(ctx context.Context) error {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_USER_SERVICE)
	if err != nil {
		return err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewMiniProgramServiceClient(conn)
	resp, err := client.ClearAccessTokenCache(ctx, &pb.ClearAccessTokenCacheRequest{})
	if err != nil {
		return err
	}
	if resp == nil || !resp.IsSuccess {
		return errors.New("清缓存失败")
	}
	return nil
}

// GetMpMobile
// 获取手机号
func (r *mpRepository) GetMpMobile(ctx context.Context, request *pb.GetMobileRequest) (*pb.GetMobileResponse, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_USER_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewMiniProgramServiceClient(conn)
	return client.GetMobile(ctx, request)
}
